import os from '@packages/lib-os';

import JSBridge from './api';
import { wptBridgeJsCallNative, wptBridgeRegisterForNativeJs } from './core';
import share from './share';
import { isWPTApp } from './util';

export { initWptBridge } from './global';

export const wptBridge = {
    ...share,
    wptBridgeRegisterForNativeJs,
    wptBridgeJsCallNative,
    bridgeTest: () =>
        wptBridgeJsCallNative(
            'bridgeTest',
            { a: 1, b: [1, 2, 3] },
            (res) => console.log(res.data.c, res.data.num),
            () => console.log('fail')
        ),
    /**
     * app设置消息推送函数
     * @param {0|1|2} param 参数：0 查询状态 1 弹出弹层 2 跳转原生页面 3 签到界面弹窗 4 出价完成之后弹窗
     * @param {(open: number) => void} successFn 查询状态参数回调，0未开启 1已开启
     */
    handleAppNotification: (param, successFn) => {
        if (os.wptAppVerison >= 350) {
            wptBridgeJsCallNative('handleAppNotification', { action: param }, successFn);
        }
    },

    /**
     * app播放视频
     * @param {{ src: string; cover: string; }} param 参数：src 视频地址 url 视频封面 cover
     */
    playVideo: ({ src, cover }) => {
        if (os.wptAppVerison >= 352 && os.ios) {
            wptBridgeJsCallNative('wptAppVideoPlay', { src, cover });
            return true;
        }
        return false;
    },

    /**
     * APP内视频预加载
     * @param videos [{url: '', cover: ''}]
     */
    preloadVideo: (videos = []) => {
        const videoInfos = videos
            .map(({ url: videoUrl = '', cover: videoCover = '' } = {}) => ({
                videoUrl,
                videoCover,
            }))
            .filter((item) => !!item.videoUrl);
        os.wptAppVerison >= 365 &&
            videoInfos.length &&
            wptBridgeJsCallNative('wptVideoPreCache', {
                videoInfos,
            });
    },

    /**
     * 鉴真阁远程鉴定播放视频
     * @param  [{identUri: '', liveUniqUri: ''}]
     */
    playIdentVideo: (param) => {
        if (WPT.os.jzg || (WPT.os.wpt && os.wptAppVerison >= 395)) {
            wptBridgeJsCallNative('playIdentVideo', param);
        }
    },

    /**
     * 鉴真阁远程鉴定大师连线
     * @param  [{identUri: '', littleAnchorUid: '', connectStatus: ''}]
     */
    jzgIdentConnect: (param) => {
        wptBridgeJsCallNative('jzgIdentConnect', param);
    },

    /**
     * 鉴真阁远程鉴定用户接听连线
     * @param  [{littleAnchorUid: '', identUri: ''}]
     */
    jzgReceiveConnect: (param) => {
        wptBridgeJsCallNative('jzgReceiveConnect', param);
    },

    setVideoPosition: (position = {}) => {
        const { x = 0, y = 0, width = 0, height = 0 } = position;
        os.ios &&
            os.wptAppVerison >= 365 &&
            wptBridgeJsCallNative('wptVideoCellLocation', {
                x,
                y,
                width,
                height,
            });
    },

    closeWebView: (param, successFn) => {
        if (os.wptAppVerison >= 355) {
            wptBridgeJsCallNative('closeWebView', { action: param }, successFn);
            return true;
        }
        return false;
    },

    // 手机号绑定成功后将 userinfo 传给 APP
    bindTelCallAPP: (param) => {
        if (os.wptAppVerison >= 358) {
            wptBridgeJsCallNative('userInfoFromBindTel', { userinfo: param });
        }
    },

    // 新增/编辑地址
    editAddress: (address, success) => {
        if (os.wptAppVerison >= 360) {
            wptBridgeJsCallNative('editAddress', { address }, success);
            return true;
        }
        return false;
    },

    /**
     * app唤起微信支付分
     */
    handleWeixinPayScore: ({ query, businessType }, successFn) => {
        if (os.wptAppVerison >= 361) {
            wptBridgeJsCallNative('handleWeixinPayScore', { query, businessType }, successFn);
            return true;
        }
        return false;
    },

    // 风险用户校验结果通知 APP
    riskverifyCallAPP: (param) => {
        if (os.wptAppVerison >= 360) {
            wptBridgeJsCallNative('userVerifyFinished', { code: param });
            return true;
        }
        return false;
    },

    // native 视频上传
    uploadVideo: ({ bType, timeLimit, callback, needNickname = true, deleteWptWaterMark = false }) => {
        if (os.wptAppVerison >= 361) {
            wptBridgeJsCallNative(
                'uploadVideo',
                { bType, timeLimit, watermarkName: needNickname ? WPT.userinfo.nickname : '', deleteWptWaterMark },
                callback
            );
        }
    },

    /**
     * 检测用户是否安装微信app
     * @param {(open: number) => void} successFn 查询状态参数回调，0未安装 1已安装
     */
    checkWeixinAppInstalled: (successFn) => {
        if (os.wptAppVerison >= 367) {
            wptBridgeJsCallNative('checkWeixinAppInstalled', {}, successFn);
            return true;
        }
        return false;
    },
    // 改变statusBar主题
    changeStatusBarTheme: ({ isBlack = 1, backgroundColor = null }) => {
        if (os.wptAppVerison >= 367) {
            wptBridgeJsCallNative('wptUpdateStatusBarStyle', { isBlack, backgroundColor });
        }
    },
    // 传递需要改变webview底色的配置
    updateWebViewBackgroundConfig: (config) => {
        if (os.wptAppVerison >= 367) {
            wptBridgeJsCallNative('wptUpdateWebViewBackgroundConfig', { config });
        }
    },
    // 重置页面底色
    resetWebViewBackgroundColor: () => {
        if (os.wptAppVerison >= 367) {
            wptBridgeJsCallNative('wptResetWebViewBackgroundColor');
        }
    },
    // 通知app js已经准备好了
    wptH5JSPrepareed: () => {
        if (os.wptAppVerison >= 377) {
            wptBridgeJsCallNative('wptH5JSPrepareed');
        }
    },

    // app保存视频功能
    /**
     * @param videoUrl  视频链接
     * @param { videoUrl: '', tips: '' } path
     * @returns
     */
    wptDownloadVideo: (path) => {
        if (!path) return;
        let params = {};
        if (typeof path === 'string') {
            params.videoUrl = path;
        } else if (typeof path === 'object' && path.videoUrl) {
            params = {
                ...path,
            };
        }
        wptBridgeJsCallNative('wptDownloadVideo', { ...params });
    },

    // app保存图片功能
    /**
     * @param imgUrl  视频链接
     * @param { imgUrl: '', tips: '' } path
     * @returns
     */
    wptDownloadImage: (path) => {
        if (!path) return;
        let params = {};
        if (typeof path === 'string') {
            params.imgUrl = path;
        } else if (typeof path === 'object' && path.imgUrl) {
            params = {
                ...path,
            };
        }
        if (os.wptAppVerison >= 371) {
            wptBridgeJsCallNative('wptDownloadImage', { ...params });
        } else {
            window.wx &&
                window.wx.downloadImage &&
                window.wx.downloadImage({
                    serverId: params.imgUrl,
                });
        }
    },

    /**
     * 支付弹窗sdk
     * @param {Boolean} onlyForEnsure 检查是否可用
     * @param {String} orderNo 订单号
     * @param {String} title 支付弹窗标题
     * @param {String} tips 弹窗中部提示
     * @param {Function} success 回调
     */
    paySdk: ({ onlyForEnsure = false, ...other }, success) => {
        const enable = (os.wjb && os.wjbVersion >= 114) || os.wptAppVerison >= 373;
        if (onlyForEnsure) {
            return enable;
        }
        if (enable) {
            wptBridgeJsCallNative('wptPaySdk', other, success);
            return true;
        }
        return false;
    },
    // 通知APP进入验证码解锁
    enterNetUnlock: () => {
        wptBridgeJsCallNative('wptH5EnterIPDeblocking');
    },
    /**
     * app播放视频
     * @param {{ enable:'yes'|'no'; }} param 参数：direct: 弹性方向 enable: yes开启 no禁用
     */
    wptBounceEnable: ({ enable }) => {
        if (os.wptAppVerison >= 378 && os.ios) {
            wptBridgeJsCallNative('wptBounceEnable', { enable });
        }
    },
    openNewWebview: (url) => {
        if (os.wpt && !os.wjb && os.wptAppVerison >= 384) {
            wptBridgeJsCallNative('wptOpenNewWindowWebView', {
                url: !/^http(s?)/.test(url) ? `https://${window.location.host}${url}` : url,
            });
            return true;
        }
        return false;
    },

    /**
     * 获取本地通讯录
     */
    wptContactsBook: (successFn) => {
        if (os.wptAppVerison >= 385) {
            wptBridgeJsCallNative('wptContactsBook', successFn);
        }
    },

    /**
     * 获取腾讯地图
     */
    wptLocation: (successFn) => {
        if (os.wptAppVerison >= 385 && !os.wjb) {
            wptBridgeJsCallNative('wptLocation', successFn);
        }
    },

    /**
     * 省市区选择列表
     */
    wptCityList: (addressParams, successFn) => {
        if (os.wptAppVerison >= 390 && !os.wjb) {
            wptBridgeJsCallNative('wptCityList', addressParams, successFn);
            return true;
        }
        return false;
    },

    /**
     * 从app获取用户当前真实手机号
     * @param {type:'token'} 获取accessToken
     * @param {type:'phone'} 获取手机号
     */
    requestRealPhone(params, success, fail) {
        // ios >= 385 或者 android >= 387 才能使用一键登录功能
        if (os.wptAppVerison >= 387 || (os.wptAppVerison >= 385 && os.ios)) {
            wptBridgeJsCallNative('getPhoneCode', params, success, fail);
        } else {
            fail && fail();
        }
    },

    /**
     * 检测用户是否安装微博app
     * @param {(open: number) => void} successFn 查询状态参数回调，0未安装 1已安装
     */
    checkWeiboAppInstalled: (successFn) => {
        if (os.wptAppVerison >= 385) {
            wptBridgeJsCallNative('checkWeiboAppInstalled', {}, successFn);
        }
    },

    // app 检查是否有最新版本
    checkNativeUpdate: () => {
        if (os.wptAppVerison >= 389) {
            wptBridgeJsCallNative('wptCheckNativeUpdate');
        }
    },

    // 查询 app 缓存大小
    getNativeCacheSize: (successFn) => {
        if (os.wptAppVerison >= 389) {
            wptBridgeJsCallNative('wptNativeCacheSize', successFn);
        }
    },

    // 清除 app 缓存
    clearNativeCache: (successFn) => {
        if (os.wptAppVerison >= 389) {
            wptBridgeJsCallNative('wptClearNativeCache', successFn);
        }
    },

    // app 提供的 webview 返回方法
    webviewBack: () => {
        if (os.wptAppVerison >= 389) {
            wptBridgeJsCallNative('wptWebviewBack');
        }
    },

    // 获取粘贴板内容
    readNativeClipboard: (successFn) => {
        if (os.wptAppVerison >= 389) {
            wptBridgeJsCallNative('wptReadNativeClipboard', successFn);
        }
    },

    /**
     * 新app用户登录方法
     */
    newAppLogin: ({ reportPosition = '', success = () => undefined, fail = () => undefined }) => {
        if (os.wptAppVerison >= 390) {
            window.successLogin = success;
            window.failLogin = fail;

            wptBridgeJsCallNative('wptNewAppLogin', { loginSource: reportPosition });
        } else {
            WPT.showLogin(success, fail);
        }
    },

    // app 非全屏方式 打开webview
    wptOpenWebviewDisableFullscreen: ({ url, refer = '' }) => {
        if (os.wptAppVerison >= 393) {
            wptBridgeJsCallNative('wptOpenWebviewDisableFullScreen', { url, refer });
            return true;
        }
        return false;
    },

    /**
     * 检测用户是否安装支付宝app
     * @param {(open: number) => void} successFn 查询状态参数回调，0未安装 1已安装
     */
    checkAlipayAppInstalled: (successFn) => {
        if (os.wptAppVerison >= 396) {
            wptBridgeJsCallNative('checkAlipayAppInstalled', {}, successFn);
            return true;
        }
        return false;
    },

    /**
     * 唤起支付宝app授权
     */
    wptAlipayAuth: (sign, successFn) => {
        if (os.wptAppVerison >= 396) {
            wptBridgeJsCallNative('wptAlipayAuth', { sign }, successFn);
        }
    },

    /**
     * 展示拍品详情页直播小窗口
     * @param userinfoUri 直播间
     * @param pullUrl 拉流地址
     * @param pushScene 直播间类型
     * @param orientation 视频横竖屏
     * @param onClose 关闭小窗回调
     * @return {boolean}
     */
    showFloatLiveWindow: ({ uri, playUrl, pushScene, orientation, r, c, position }, onClose = () => undefined) => {
        if (os.wptAppVerison >= 400) {
            wptBridgeJsCallNative(
                'showFloatWindow',
                {
                    userinfoUri: uri,
                    pullUrl: playUrl,
                    pushScene,
                    orientation,
                    position,
                    r,
                    c,
                },
                onClose
            );
            return true;
        }
        return false;
    },

    /**
     * 关闭直播小窗
     * @param userinfoUri
     * @param onClose
     * @return {boolean}
     */
    hideFloatWindow: (userinfoUri, onClose = () => undefined) => {
        if (os.wptAppVerison >= 400) {
            wptBridgeJsCallNative('hideFloatWindow', { userinfoUri }, onClose);
            return true;
        }
        return false;
    },

    /*
        滑动验证回调
     */
    sliderCallback: (res) => {
        if (os.wptAppVerison >= 405) {
            wptBridgeJsCallNative('sliderCallback', res);
            return true;
        }
        return false;
    },
};

/**
 * 业务代码中注册函数给app调用同时调用原生方法
 *
 * @param {string} NAME 保证NAME和wptBridge中的NAME保持一致
 * @param {Function} callback
 * @returns {Function} unRegistryFn
 */
export function wptBridgeListener(NAME, callback = () => undefined, { callAtOnce = false, params = '' } = {}) {
    if (!isWPTApp) {
        return () => undefined;
    }

    const removeFuc = wptBridgeRegisterForNativeJs(NAME, callback);

    if (callAtOnce && wptBridge[NAME]) {
        wptBridge[NAME](params, callback);
    }

    return removeFuc;
}

export { wptBridgeRegisterForNativeJs };
//把JSBridge挂载到wptBridge上，方便进行全局调用
for (const key in JSBridge) {
    wptBridge[key] = JSBridge[key];
}
export default wptBridge;
